// pages/afterLogisticsAdd/afterLogisticsAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //提交按钮禁用
    disabled:false,
    //传参来的id
    id:null,
    //传参来的售后记录id
    afterssrid:null,
    //修改信息回显
    editInfo:{},
    //时间
    deliveryTime:util.timeFormat(new Date()),
    //时间选择框
    showDeliverytime:false,
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //避免表单重复提交
    code:null,
    //是否是编辑
    isEdit:false,
    //服务详情
    serviceDetails:[],
    //物流公司选择框
    showLogistics:false,
    //物流公司选择数据
    logisticsList:[],
    //自带/含物流选择框
    showType:false,
    //自带/含物流选择数据
    typeList:[{
      id:1,
      text:'含物流'
    },{
      id:2,
      text:'自带'
    }],
    //显示名字
    typeName:'',

    //领件人选择框
    showStaff:false,
    //领件人选择数据
    staffList:[],
    //搜索领件人
    valueSearchStaff:'',
    //平台id
    myAppId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    this.setData({
      code:Base64.encode(new Date() + user.userName),
      myAppId:app.globalData.myAppId
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取要修改的数据
        this.getInfo();
      }

      if(paramObj.afterssrid){
        this.setData({
          afterssrid: paramObj.afterssrid
        })
        //获取售后服务详情
        this.getAfterDetail();
      }
    }
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let editInfo=this.data.editInfo;
    let dataObj={};

    //配件方式必选
    if(!editInfo.type){
      Toast.fail('请选择配件方式');
      return;
    }

    //含物流
    if(editInfo.type==1){
      let obj=e.detail.value;

      let consignee=obj.consignee.trim();
      let contact=obj.contact.trim();
      let shippingAddress=obj.shippingAddress.trim();
      let logisticsName=obj.logisticsName.trim();
      let odd=obj.odd.trim();

      //非空验证
      if(!this.formNotEmpty(consignee,'consigneeMessage','请输入收货人')){
        return;
      }
      if(!this.formNotEmpty(contact,'contactMessage','请输入手机号')){
        return;
      }
      if(!this.formNotEmpty(shippingAddress,'shippingAddressMessage','请输入收货地址')){
        return;
      }
      if(!this.formNotEmpty(logisticsName,'logisticsNameMessage','请输入或选择物流公司')){
        return;
      }
      if(!this.formNotEmpty(odd,'oddMessage','请输入物流单号')){
        return;
      }

      //手机号格式
      if(!util.checkPhoneFormat(contact)){
        this.setData({
          contactMessage: '手机号格式错误',
          disabled:true
        })
        return;
      }

      //运费为数字
      let freight=obj.freight.trim();
      if(freight!='' && freight!=null){
        if(!(/^\d+(\.\d+)?$/.test(freight))){
          this.setData({
            freightMessage: '运费为数字',
            disabled: true
          });
          return;
        }
      }

      dataObj={
        requestToken: this.data.code,
        id: this.data.id,
        consignee: consignee,
        contact: contact,
        shippingAddress: shippingAddress,
        deliveryTime: this.data.deliveryTime,
        logisticsName: logisticsName,
        odd: odd,
        freight: Number(freight),
        remark: obj.remark,
        //售后记录表id
        afterssrid: this.data.afterssrid,
        //1物流,2自带
        type: editInfo.type
      }
    }
    //自带
    else if(editInfo.type==2){
      //领件人必选
      if(!editInfo.staff){
        Toast.fail('请选择领件人');
        return;
      }

      dataObj={
        requestToken: this.data.code,
        id: this.data.id,
        staff:editInfo.staff,
        staffName:editInfo.staffName,
        contact: editInfo.contact,
        deliveryTime: this.data.deliveryTime,
        afterssrid: this.data.afterssrid,
        type: editInfo.type
      }
    }

    let param={
      className:'afterDeliveryRecord',
      data:dataObj
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    //console.log(param);

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        //售后记录增加详情
        this.insertAfterDetail();

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取要修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterDeliveryRecord',
      data: {
        id:this.data.id,
        selectFields: ['id','consignee','contact','shippingAddress','deliveryTime','logisticsName','odd','freight','remark','afterssrid','type','staff','staffName'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        this.setData({
          editInfo: res.data.data.result[0]
        })
        //修改信息回显
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //修改信息回显
  getInputValue(){
    let info=this.data.editInfo;

    console.log('修改信息回显');
    console.log(info);

    //处理type
    let typeName='';
    if(info.type){
      if(info.type==1){
        typeName='含物流';
      }else if(info.type==2){
        typeName='自带';
      }
    }

    this.setData({
      deliveryTime: info.deliveryTime ? util.timeFormat(info.deliveryTime) : this.data.deliveryTime,
      afterssrid: info.afterssrid,
      typeName: typeName
		})
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //显示时间选择框
  onShowDeliverytime(){
    this.setData({
			showDeliverytime: true
    })
  },

  //隐藏时间选择框
  onCloseDeliverytime(){
    this.setData({
			showDeliverytime: false
    })
  },

  //确认时间
  onConfirmDeliverytime(e) {
    this.setData({
      currentDate: e.detail,
      deliveryTime:util.timeFormat(e.detail),
    })
    this.onCloseDeliverytime();
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //获取售后服务详情
  getAfterDetail(){
    let param = {
      isAuth: false,
      className: 'afterSaleServiceRecord',
      data: {
        id:this.data.afterssrid,
        selectFields: ['id','serviceDetails']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        this.setData({
          serviceDetails: result[0].serviceDetails
        })
      }
    }).catch((error) => {
    })
  },

  //售后记录增加详情
  insertAfterDetail(){
    let td=this.data;
    let user = app.globalData.userInfo;
    let serviceDetails=td.serviceDetails;

    if(td.isEdit){
      serviceDetails.push({
        content: user.userName + "修改物流信息",
        datetime: util.timeFormat(new Date())
      });
    }else{
      serviceDetails.push({
        content: user.userName + "添加物流信息",
        datetime: util.timeFormat(new Date())
      });
    }

    let param={
      className:'afterSaleServiceRecord',
      data:{
        id:td.afterssrid,
        serviceDetails:serviceDetails
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //显示物流公司选择框
  onShowLogistics(){
    this.setData({
      showLogistics: true
    })
    this.getLogisticsList();
  },

  //查询物流公司
  getLogisticsList(){
    let param = {
      isAuth: false,
      className: 'logisticsCompany',
      data: {
        searchAll: true,
        selectFields: ['id', 'name']
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          logisticsList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏物流公司选择框
  onCloseLogistics(){
    this.setData({
			showLogistics: false
    })
  },

  //确认物流公司
  onConfirmLogistics(e){
    let logisticsName='editInfo.logisticsName';
    this.setData({
      [logisticsName]: e.detail.value.text,
      logisticsNameMessage: '',
      disabled: false
    })
    this.onCloseLogistics();
  },

  //物流单号扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let odd='editInfo.odd';
        _this.setData({
          [odd]: res.result
        })
      }
    })
  },

  //显示自带/含物流选择框
  onShowType(){
    this.setData({
			showType: true
    })
  },

  //隐藏自带/含物流选择框
  onCloseType(){
    this.setData({
      showType: false,
      disabled:false
    })
  },

  //确认自带/含物流
  onConfirmType(e){
    let type='editInfo.type';
    this.setData({
      [type]:e.detail.value.id,
      typeName:e.detail.value.text
    })
    this.onCloseType();
  },

  //显示领件人选择框
  onShowStaff(){
    this.setData({
			showStaff: true
    })
    this.getStaffList();
  },

  //查询领件人
  getStaffList(){
    this.setData({
      staffList: []
    })

    let param = {
      isAuth: true,
      className: 'servicePersonal',
      data:{
        searchAll:true,
        selectFields: ['id','serviceName','telephone','type'],
        sort: {
          id: -1
        },
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    //模糊查询
    if(this.data.valueSearchStaff){
      param.data.serviceName='%' + this.data.valueSearchStaff + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.serviceName,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          staffList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏领件人选择框
  onCloseStaff(){
    this.setData({
      showStaff: false,
      valueSearchStaff:'',
      disabled:false
    })
  },

  //确认领件人
  onConfirmStaff(e){
    let obj=e.detail.value.obj;
    let staff='editInfo.staff';
    let staffName='editInfo.staffName';
    let contact='editInfo.contact';

    this.setData({
      [staff]:e.detail.value.id,
      [staffName]:e.detail.value.text,
      [contact]:obj.telephone
    })
    this.onCloseStaff();
  },

  //搜索领件人
  onChangeStaff(e){
    this.setData({
      valueSearchStaff: e.detail
    })
    this.getStaffList();
  },

  //跳转添加售后人员
  goToAddStaff(){
    wx.navigateTo({
      url: "/packageA/pages/servicePersonalAdd/servicePersonalAdd"
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
